package com.xo.user.service.impl;

import com.xo.common.Result.ResultResponse;
import com.xo.common.enums.ResultEnum;
import com.xo.common.enums.SysUserVerifyStatusEnum;
import com.xo.common.pojo.dto.req.LoginDto;
import com.xo.common.pojo.dto.req.RegisterDto;
import com.xo.common.pojo.entity.SysUserEntity;
import com.xo.common.until.idGenerateUntil;
import com.xo.user.controller.LoginUser;
import com.xo.user.convert.LoginConvert;
import com.xo.user.mapper.LoginMapper;
import com.xo.user.service.LoginService;
import com.xo.user.until.JwtUtil;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginMapper loginMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private AuthenticationManager authenticationManager;

    @Override
    public ResultResponse<Object> register(RegisterDto registerDto) {

        //1.验证手机号码是否已注册
        int count = loginMapper.selectCountByPhone(registerDto.getPhone());
        if (count > 0) {
            return ResultResponse.fail(ResultEnum.PHONE_ALREADY_EXIST.getMessage());
        }

        //2.验证用户名是否存在
        int num = loginMapper.selectCountByUsername(registerDto.getUsername());
        if (num > 0) {
            return ResultResponse.fail(ResultEnum.USERNAME_ALREADY_EXIST.getMessage());
        }

        //3.生成用户
        SysUserEntity sysUserEntity = LoginConvert.INSTANCE.RegisterDtoToSysUserEntity(registerDto);

        //新创建的用户都为待审核状态
        sysUserEntity.setVerifyStatus(SysUserVerifyStatusEnum.PENDING.getCode());
        sysUserEntity.setTenantId(idGenerateUntil.generateTenantId());
        sysUserEntity.setPassword(passwordEncoder.encode(registerDto.getPassword()));
        int number = loginMapper.insert(sysUserEntity);
        if (number > 0) {
            return ResultResponse.success(ResultEnum.REGISTER_SUCCESS.getMessage());
        }

        return ResultResponse.fail(ResultEnum.REGISTER_FAIL.getMessage());
    }

    @Override
    public ResultResponse<Object> login(LoginDto loginDto) {
        // 生成一个包含账号密码的认证信息
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());
        // AuthenticationManager校验这个认证信息，返回一个已认证的Authentication
        Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        // 将返回的Authentication存到上下文中
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 获取认证后的用户
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();

        String jwt = JwtUtil.createJWT(loginUser.getTenantId().toString(), JwtUtil.JWT_TTL, JwtUtil.getUUID());

        return ResultResponse.success("登录成功",jwt);
    }


}
